package com.liqiye.paymanager.service.payment;

import com.liqiye.paymanager.bean.common.ConvertedResponse;
import com.liqiye.paymanager.bean.common.ExchangerateResponse;
import com.liqiye.paymanager.bean.common.FrankfurterResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * 货币转换
 */
@Service
public class CurrencyConverterService {

    // 使用 exchangerate.host 免费 API 来实时获取汇率（每个月只能100次）
    @Value("${currency.converter.exchangerate.accessKey}")
    private String exchangerate_ak;

    private final RestTemplate restTemplate;

    public CurrencyConverterService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public ConvertedResponse convert(String from, String to, BigDecimal amount) {
        String url = String.format(
                "https://api.frankfurter.app/latest?from=%s&to=%s&amount=%s",
                from.toUpperCase(), to.toUpperCase(), amount
        );

        FrankfurterResponse response = restTemplate.getForObject(url, FrankfurterResponse.class);
        if (response == null || response.getRates() == null || !response.getRates().containsKey(to.toUpperCase())) {
            throw new IllegalArgumentException("汇率转换失败或币种不受支持");
        }

        BigDecimal rate = response.getRates().get(to.toUpperCase());
        return new ConvertedResponse(
                response.getBase(),
                to.toUpperCase(),
                response.getAmount(),
                rate,
                response.getDate()
        );
    }

    public BigDecimal convert2(String from, String to, BigDecimal amount) {
        String url = String.format(
            "https://api.exchangerate.host/convert?access_key=%s&from=%s&to=%s&amount=%s",
                exchangerate_ak, from.toUpperCase(), to.toUpperCase(), amount
        );

        ResponseEntity<ExchangerateResponse> response = restTemplate.getForEntity(url, ExchangerateResponse.class);

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null && response.getBody().isSuccess()) {
            return response.getBody().getResult();
        } else {
            throw new IllegalArgumentException("汇率获取失败或不支持的币种: " + from + " → " + to);
        }
    }

}
